﻿using LJ.Abstractions.Extensions;
using LJ.AspNetCore.Abstractions.Pack;
using LJ.WebApi.Abstractions.Pack;
using LJ.WebApi.Mvc.Extensions;
using LJ.WebApi.Mvc.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;

namespace LJ.WebApi.Mvc.Pack;

public abstract class WebApiMvcPackBase: AspNetCorePackBase, IWebApiPack
{

    public override void Add(IAspNetCorePackContext aspNetCorePackContext)
    {

        //Json 序列化/反序列化 配置
        aspNetCorePackContext.DependencyManager.ServiceCollection.Configure<JsonOptions>(options =>
        {
            //枚举
            options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
        });

        //启动Mvc
        aspNetCorePackContext.DependencyManager.ServiceCollection.AddMvc();
        aspNetCorePackContext.DependencyManager.ServiceCollection.AddEndpointsApiExplorer();

        var partManager = aspNetCorePackContext.DependencyManager.ServiceCollection.GetSingletonInstance<ApplicationPartManager>();
        // 解决项目类型为 <Project Sdk="Microsoft.NET.Sdk"> 不能加载 API 问题，默认支持 <Project Sdk="Microsoft.NET.Sdk.Web">
        foreach (var assembly in aspNetCorePackContext.ReflectionManager.GetAssemblies())
        {
            if (partManager.ApplicationParts.Any(u => u.Name != assembly.GetName().Name))
            {
                partManager.ApplicationParts.Add(new AssemblyPart(assembly));
            }
        }

        aspNetCorePackContext.ConfigManager.Add<WebApiConfig>("WebApi");

        var webApiHandlerManager = new WebApiHandlerManager(aspNetCorePackContext.ReflectionManager);

        aspNetCorePackContext.DependencyManager.ServiceCollection.AddSingleton<IWebApiHandlerManager>(webApiHandlerManager);

        //动态WebApi
        aspNetCorePackContext.AddDynamicWebApi();

        // OpenApi
        aspNetCorePackContext.AddOpenApi();

        // 统一处理
        aspNetCorePackContext.AddUnifyData();
    }

    public override void Use(IAspNetCorePackProvider aspNetCorePackProvider)
    {

        //启用 OpenApi
        aspNetCorePackProvider.UseOpenApi();

        //// 放在前面，确保所有请求都通过HTTPS
        //aspNetCorePackProvider.ApplicationBuilder.UseHttpsRedirection();
        // 确定路由
        aspNetCorePackProvider.ApplicationBuilder.UseRouting();
       
        // 映射控制器
        aspNetCorePackProvider.EndpointRouteBuilder.MapControllers();


    }
}
